import { Notification } from 'element-ui'

var messages = [];
var parses = {};
var notifications = [];

export function m(key, equal) {
  if (undefined == key) {
    return "";
  }
  if (typeof key !== 'string') {
    return key;
  }
  if (undefined == equal) {
    equal = true;
  }
  var ok = key;
  if (parses[ok]) {
    return parses[ok];
  }
  
  if (0 == messages.length && localStorage.messages && 'undefined' != localStorage.messages) {
    messages = JSON.parse(localStorage.messages);
  }
  if (0 == messages.length) {
    return key;
  }

  if (equal && messages[key.toLowerCase()]) {
    return messages[key.toLowerCase()];
  }
  var regex = /__(.+?)__/g;
  var params = [];
  var match;
  while (match = regex.exec(key)) {
    params.push(match[1]);
  }
  for (var k in params) {
    if (typeof params[k] == 'string') {
      var m = params[k].toLowerCase();
      var text = messages[m];
      key = key.replace("__" + m + "__", text ? text : m);
    }
  }
  parses[ok] = key;

  return key;
}

export function f(key) {
  if ( ! key) {
    return "";
  }
  return "__" + key.replace("\.", "_").replace(/(^_+)|(_+$)/g, "") + "__";
}

export function notify(notification) {
  if ( ! notification['position']) {
    notification['position'] = 'bottom-right';
  }
  notifications.push(Notification(notification));
}
export function closeAllNotifications() {
  for (var i = 0; i < notifications.length; i++) {
    notifications[i].close();
  }
  notifications = [];
}